package batch.process.cdi;

import java.util.Collection;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import batch.process.cdi.bean.CDIBean;
import batch.process.core.BaseThread;
import batch.process.utils.BatchProcessUtils;
import batch.process.utils.Constant;

public class CDIRetrieverJob extends BaseThread {

	private CDIRetriever retriever = null;
	
	public CDIRetrieverJob(CountDownLatch finalizado) {
		super(finalizado);		
	}
	
	public void run() {
		
		this.setName("CDIRetrieverJob");
		logger.info("Initializing CDI Retriever Job main thread run ...",
				CDIRetrieverJob.class);		
		try {		
			while (!finaliza) {
				try {
					logger.info(this.getName() + " thread awake ... " ,CDIRetrieverJob.class);
					
					BatchProcessUtils.loadProperties();
					
					retriever = new CDIRetriever();										
					Collection<CDIBean> list = retriever.retrieveCDI(new Date());
					retriever = null;
					
					if (list != null && list.isEmpty()) {
						logger.info(list.toString(), CDIRetrieverJob.class);
					}										
					
					logger.info("Sending " + this.getName() + " thread to sleep for " + 
							Constant.THREAD_SLEEP_TIME + " hours " ,CDIRetrieverJob.class);
					Thread.sleep(Constant.THREAD_SLEEP_TIME*60*60*1000);					
				} catch (InterruptedException e) {				
					e.printStackTrace();										
					logger.error("Error on CDI Retriever Job main thread : " + e,
							CDIRetrieverJob.class);
				} finally {
					retriever.logout();
					retriever.disconnect();
					retriever = null;
				}
			}			
		} catch (Exception e) {
			logger.error("Error processing thread ..." + e, CDIRetrieverJob.class);
		} finally {
			logger.info("Finalizing CDI Retriever Job main thread in 10 sec ...",CDIRetrieverJob.class);	
			try {
				finalizado.await(10, TimeUnit.SECONDS);
			} 
			catch (InterruptedException e1) {				
				e1.printStackTrace();
				logger.error("Error upon shutting down CDI Retriever Job main thread :" + e1,
						CDIRetrieverJob.class);
			}
			
			// finaliza as threads de copia			
			logger.info("CDI Retriever Job main thread terminated. Shutting down ...",
					CDIRetrieverJob.class);
			super.run();
		}
	}

}
